package com.wing.wecom.util.wx;

import com.wing.wecom.model.request.ApproveForm;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

public class WxUtil {

    /**
     * 解析企业微信发来的请求（xmlStr）,获取请求参数
     * @param xmlStr
     * @return
     * @throws Exception
     */
    public static ApproveForm parseXml(String xmlStr) {
        // 将解析结果存储在  审批数据存储表单  中
        ApproveForm approveForm = new ApproveForm();
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
            Element root = doc.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();

            // 3.遍历所有的子节点
            for (Element e : elementList) {
                if (e.getName().equals("Event")) {
                    approveForm.setEvent(e.getText());
                }

                if(StringUtils.isBlank(e.getText())){
                    Element approvalInfo = root.element("ApprovalInfo");
                    elementList = approvalInfo.elements();
                    List<ApproveForm.SpRecord> spRecords = new ArrayList<>();
                    List<ApproveForm.Notifyer> notifyers = new ArrayList<>();
                    List<ApproveForm.Comments> comments = new ArrayList<>();
                    for (Element e1 : elementList) {
                        if(e1.getName().equals("SpNo")){
                            approveForm.setSpNo(e1.getText());
                        }else if(e1.getName().equals("SpName")){
                            approveForm.setSpName(e1.getText());
                        }else if(e1.getName().equals("SpStatus")){
                            approveForm.setSpStatus(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("TemplateId")){
                            approveForm.setTemplateId(e1.getText());
                        }else if(e1.getName().equals("ApplyTime")){
                            approveForm.setApplyTime(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("StatuChangeEvent")){
                            approveForm.setStatuChangeEvent(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("Applyer")){ // 申请人信息
                            ApproveForm.Applyer applyerForm = new ApproveForm.Applyer();
                            elementList = e1.elements();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("UserId")){
                                    applyerForm.setUserId(e2.getText());
                                }else if(e2.getName().equals("Party")){
                                    applyerForm.setParty(Integer.parseInt(e2.getText()));
                                }
                            }
                            approveForm.setApplyer(applyerForm);
                        }else if(e1.getName().equals("SpRecord")){ // 审批流程信息，可能有多个审批节点。
                            ApproveForm.SpRecord spRecordForm = new ApproveForm.SpRecord();
                            elementList = e1.elements();
                            List<ApproveForm.SpRecord.Details> details = new ArrayList<>();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("SpStatus")){
                                    System.out.println(e2.getText());
                                    spRecordForm.setSpStatus(Integer.parseInt(e2.getText()));
                                }else if(e2.getName().equals("ApproverAttr")){
                                    spRecordForm.setApproverAttr(Integer.parseInt(e2.getText()));
                                }else if(e2.getName().equals("Details")){
                                    ApproveForm.SpRecord.Details detailsForm = new ApproveForm.SpRecord.Details();
                                    elementList = e2.elements();
                                    for (Element e3 : elementList) {
                                        if(e3.getName().equals("Speech")){
                                            detailsForm.setSpeech(e3.getText());
                                        }else if(e3.getName().equals("SpStatus")){
                                            detailsForm.setSpStatus(Integer.parseInt(e3.getText()));
                                        }else if(e3.getName().equals("SpTime")){
                                            detailsForm.setSpTime(Integer.parseInt(e3.getText()));
                                        }else if(e3.getName().equals("Attach")){
                                            detailsForm.setAttach(e3.getText());
                                        }else if(e3.getName().equals("Approver")){
                                            ApproveForm.SpRecord.Details.Approver approverForm = new ApproveForm.SpRecord.Details.Approver();
                                            elementList = e3.elements();
                                            for (Element e4 : elementList) {
                                                if(e4.getName().equals("UserId")){
                                                    approverForm.setUserId(e4.getText());
                                                }
                                            }
                                            detailsForm.setApprover(approverForm);
                                        }
                                    }
                                    details.add(detailsForm);
                                }
                            }
                            spRecordForm.setDetails(details);
                            spRecords.add(spRecordForm);
                        }else if(e1.getName().equals("Notifyer")){ // 抄送信息，可能有多个抄送节点
                            ApproveForm.Notifyer notifyerForm = new ApproveForm.Notifyer();
                            elementList = e1.elements();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("UserId")){
                                    notifyerForm.setUserId(e2.getText());
                                }
                            }
                            notifyers.add(notifyerForm);
                        }else if(e1.getName().equals("Comments")){ // 审批申请备注信息，可能有多个备注节点
                            ApproveForm.Comments commentsForm = new ApproveForm.Comments();
                            if(e1 != null){
                                elementList = e1.elements();
                                for (Element e2 : elementList) {
                                    if(e2.getName().equals("CommentUserInfo")){
                                        ApproveForm.Comments.CommentUserInfo commentUserInfoForm = new ApproveForm.Comments.CommentUserInfo();
                                        List<Element> elementList2 = e2.elements();
                                        for (Element e3 : elementList2) {
                                            if(e3.getName().equals("UserId")){
                                                commentUserInfoForm.setUserId(e3.getText());
                                            }
                                        }
                                        commentsForm.setCommentUserInfo(commentUserInfoForm);
                                    }else if(e2.getName().equals("CommentTime")){
                                        commentsForm.setCommentTime(Integer.parseInt(e2.getText()));
                                    }else if(e2.getName().equals("CommentContent")){
                                        commentsForm.setCommentContent(e2.getText());
                                    }else if(e2.getName().equals("CommentId")){
                                        commentsForm.setCommentId(e2.getText());
                                    }
                                }
                            }
                            comments.add(commentsForm);
                        }
                    }
                    approveForm.setNotifyers(notifyers);
                    approveForm.setSpRecords(spRecords);
                    approveForm.setComments(comments);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return approveForm;
    }

    public static void main(String[] args){
        String xml = "<xml><ToUserName><![CDATA[wwbefee404a6a5cadf]]></ToUserName>" +
                "<FromUserName><![CDATA[sys]]></FromUserName>" +
                "<CreateTime>1638785566</CreateTime>" +
                "<MsgType><![CDATA[event]]></MsgType>" +
                "<Event><![CDATA[sys_approval_change]]></Event>" +
                "<AgentID>3010040</AgentID>" +
                "<ApprovalInfo>" +
                "   <SpNo>202112060008</SpNo>" +
                "   <SpName><![CDATA[加班]]></SpName>" +
                "   <SpStatus>3</SpStatus>" +
                "   <TemplateId><![CDATA[3TkZsZMXLGk3k4hNqhACRuc2ZCvLsx4WgR5mwBRq]]></TemplateId>" +
                "   <ApplyTime>1638784966</ApplyTime>" +
                "   <Applyer>" +
                "       <UserId><![CDATA[1462666849074864130]]></UserId>" +
                "       <Party><![CDATA[22]]></Party>" +
                "   </Applyer>" +
                "   <SpRecord>" +
                "       <SpStatus>3</SpStatus>" +
                "       <ApproverAttr>1</ApproverAttr>" +
                "       <Details>" +
                "           <Approver>" +
                "               <UserId><![CDATA[ZiJi]]></UserId>" +
                "           </Approver>" +
                "           <Speech><![CDATA[]]></Speech>" +
                "           <SpStatus>3</SpStatus>" +
                "           <SpTime>1638785566</SpTime>" +
                "       </Details>" +
                "   </SpRecord>" +
                "   <SpRecord>" +
                "       <SpStatus>2</SpStatus>" +
                "       <ApproverAttr>1</ApproverAttr>" +
                "       <Details>" +
                "           <Approver>" +
                "               <UserId><![CDATA[Liu]]></UserId>" +
                "           </Approver>" +
                "           <Speech><![CDATA[]]></Speech>" +
                "           <SpStatus>3</SpStatus>" +
                "           <SpTime>1638785566</SpTime>" +
                "       </Details>" +
                "   </SpRecord>" +
                "   <Notifyer>" +
                "       <UserId><![CDATA[ZiJi]]></UserId>" +
                "   </Notifyer>" +
                "   <StatuChangeEvent>3</StatuChangeEvent>" +
                "</ApprovalInfo></xml>";
        // 将解析结果存储在  审批数据存储表单  中
        ApproveForm approveForm = new ApproveForm();
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            Element root = doc.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();

            // 3.遍历所有的子节点
            for (Element e : elementList) {
                if (e.getName().equals("Event")) {
                    approveForm.setEvent(e.getText());
                }

                if(StringUtils.isBlank(e.getText())){
                    Element approvalInfo = root.element("ApprovalInfo");
                    elementList = approvalInfo.elements();
                    List<ApproveForm.SpRecord> spRecords = new ArrayList<>();
                    List<ApproveForm.Notifyer> notifyers = new ArrayList<>();
                    List<ApproveForm.Comments> comments = new ArrayList<>();
                    for (Element e1 : elementList) {
                        if(e1.getName().equals("SpNo")){
                            approveForm.setSpNo(e1.getText());
                        }else if(e1.getName().equals("SpName")){
                            approveForm.setSpName(e1.getText());
                        }else if(e1.getName().equals("SpStatus")){
                            approveForm.setSpStatus(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("TemplateId")){
                            approveForm.setTemplateId(e1.getText());
                        }else if(e1.getName().equals("ApplyTime")){
                            approveForm.setApplyTime(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("StatuChangeEvent")){
                            approveForm.setStatuChangeEvent(Integer.parseInt(e1.getText()));
                        }else if(e1.getName().equals("Applyer")){ // 申请人信息
                            ApproveForm.Applyer applyerForm = new ApproveForm.Applyer();
                            elementList = e1.elements();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("UserId")){
                                    applyerForm.setUserId(e2.getText());
                                }else if(e2.getName().equals("Party")){
                                    applyerForm.setParty(Integer.parseInt(e2.getText()));
                                }
                            }
                            approveForm.setApplyer(applyerForm);
                        }else if(e1.getName().equals("SpRecord")){ // 审批流程信息，可能有多个审批节点。
                            ApproveForm.SpRecord spRecordForm = new ApproveForm.SpRecord();
                            elementList = e1.elements();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("SpStatus")){
                                    System.out.println(e2.getText());
                                    spRecordForm.setSpStatus(Integer.parseInt(e2.getText()));
                                }else if(e2.getName().equals("ApproverAttr")){
                                    spRecordForm.setApproverAttr(Integer.parseInt(e2.getText()));
                                }else if(e2.getName().equals("Details")){
                                    elementList = e2.elements();
                                    List<ApproveForm.SpRecord.Details> details = new ArrayList<>();
                                    for (Element e3 : elementList) {
                                        ApproveForm.SpRecord.Details detailsForm = new ApproveForm.SpRecord.Details();
                                        if(e3.getName().equals("Speech")){
                                            detailsForm.setSpeech(e3.getText());
                                        }else if(e3.getName().equals("SpStatus")){
                                            detailsForm.setSpStatus(Integer.parseInt(e3.getText()));
                                        }else if(e3.getName().equals("SpTime")){
                                            detailsForm.setSpTime(Integer.parseInt(e3.getText()));
                                        }else if(e3.getName().equals("Attach")){
                                            detailsForm.setAttach(e3.getText());
                                        }else if(e3.getName().equals("Approver")){
                                            ApproveForm.SpRecord.Details.Approver approverForm = new ApproveForm.SpRecord.Details.Approver();
                                            elementList = e3.elements();
                                            for (Element e4 : elementList) {
                                                if(e4.getName().equals("UserId")){
                                                    approverForm.setUserId(e4.getText());
                                                }
                                            }
                                            detailsForm.setApprover(approverForm);
                                        }
                                        details.add(detailsForm);
                                    }
                                    spRecordForm.setDetails(details);
                                }
                            }
                            spRecords.add(spRecordForm);
                        }else if(e1.getName().equals("Notifyer")){ // 抄送信息，可能有多个抄送节点
                            ApproveForm.Notifyer notifyerForm = new ApproveForm.Notifyer();
                            elementList = e1.elements();
                            for (Element e2 : elementList) {
                                if(e2.getName().equals("UserId")){
                                    notifyerForm.setUserId(e2.getText());
                                }
                            }
                            notifyers.add(notifyerForm);
                        }else if(e1.getName().equals("Comments")){ // 审批申请备注信息，可能有多个备注节点
                            ApproveForm.Comments commentsForm = new ApproveForm.Comments();
                            if(e1 != null){
                                elementList = e1.elements();
                                for (Element e2 : elementList) {
                                    if(e2.getName().equals("CommentUserInfo")){
                                        ApproveForm.Comments.CommentUserInfo commentUserInfoForm = new ApproveForm.Comments.CommentUserInfo();
                                        List<Element> elementList2 = e2.elements();
                                        for (Element e3 : elementList2) {
                                            if(e3.getName().equals("UserId")){
                                                commentUserInfoForm.setUserId(e3.getText());
                                            }
                                        }
                                        commentsForm.setCommentUserInfo(commentUserInfoForm);
                                    }else if(e2.getName().equals("CommentTime")){
                                        commentsForm.setCommentTime(Integer.parseInt(e2.getText()));
                                    }else if(e2.getName().equals("CommentContent")){
                                        commentsForm.setCommentContent(e2.getText());
                                    }else if(e2.getName().equals("CommentId")){
                                        commentsForm.setCommentId(e2.getText());
                                    }
                                }
                            }
                            comments.add(commentsForm);
                        }
                    }
                    approveForm.setNotifyers(notifyers);
                    approveForm.setSpRecords(spRecords);
                    approveForm.setComments(comments);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(approveForm);
    }
}